package cn.thread.pool.dynamic.thread.pool.sdk.trigger.job;
import cn.thread.pool.dynamic.thread.pool.sdk.domain.IDynamicThreadPoolService;
import cn.thread.pool.dynamic.thread.pool.sdk.register.Iregister;
import cn.thread.pool.dynamic.thread.pool.sdk.domain.model.entity.ThreadPoolConfigEntity;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.List;

/**
 * @author: xiaoxie
 * create: 2025-02-11 21:57
 * @BelongsProject: custom-dynamic-thread-pool
 * @BelongsPackage: cn.thread.pool.dynamic.thread.pool.sdk.trigger.job
 * description: 定时执行redis注册任务
 */
public class redisRegisterJob {
    private Logger logger = LoggerFactory.getLogger(redisRegisterJob.class);

    private final IDynamicThreadPoolService dynamicThreadPoolService;

    private final Iregister redisRegister;

    public redisRegisterJob(IDynamicThreadPoolService dynamicThreadPoolService, Iregister redisRegister) {
        this.dynamicThreadPoolService = dynamicThreadPoolService;
        this.redisRegister = redisRegister;
    }

    /**
     * 每隔30秒执行一次上报任务
     */
    @Scheduled(cron = "0/30 * * * * ?")
    public void execute() {
        try {
            List<ThreadPoolConfigEntity> threadPoolConfigList = dynamicThreadPoolService.queryAllThreadPools();
            redisRegister.registerThreadPoolList(threadPoolConfigList);
            logger.info("上报的线程池配置列表为: {}", JSON.toJSONString(threadPoolConfigList));

            for (ThreadPoolConfigEntity threadPoolConfigEntity : threadPoolConfigList) {
                try {
                    redisRegister.registerThreadPoolConfigParameter(threadPoolConfigEntity);
                    logger.info("上报的线程池配置为: {}", JSON.toJSONString(threadPoolConfigEntity));
                } catch (Exception e) {
                    logger.error("Failed to register thread pool config parameter: {}", threadPoolConfigEntity, e);
                }
            }
        } catch (Exception e) {
            logger.error("Failed to execute scheduled job", e);
        }
    }
}

